"""
岗位相关路由
"""

from typing import List
from uuid import UUID, uuid4

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.auth import get_current_user
from app.database import get_db
from app.models import Position, User
from app.schemas import PositionCreate, PositionResponse

router = APIRouter(prefix="/api/positions", tags=["岗位管理"])


@router.post("/", response_model=PositionResponse, status_code=status.HTTP_201_CREATED)
def create_position(
    position_data: PositionCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    """
    创建新岗位

    Args:
        position_data: 岗位数据
        db: 数据库会话
        current_user: 当前用户

    Returns:
        PositionResponse: 创建的岗位信息

    Note:
        white_paper_tag 自动生成 UUID，用于关联知识库
    """
    # 自动生成 UUID 作为知识库标签
    white_paper_tag = str(uuid4())

    new_position = Position(
        title=position_data.title,
        jd_text=position_data.jd_text,
        white_paper_tag=white_paper_tag,
    )

    db.add(new_position)
    db.commit()
    db.refresh(new_position)

    return new_position


@router.get("/", response_model=List[PositionResponse])
def list_positions(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    """
    获取岗位列表

    Args:
        skip: 跳过的记录数
        limit: 返回的最大记录数
        db: 数据库会话
        current_user: 当前用户

    Returns:
        List[PositionResponse]: 岗位列表
    """
    positions = db.query(Position).offset(skip).limit(limit).all()
    return positions


@router.get("/{position_id}", response_model=PositionResponse)
def get_position(
    position_id: UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    """
    获取岗位详情

    Args:
        position_id: 岗位 ID
        db: 数据库会话
        current_user: 当前用户

    Returns:
        PositionResponse: 岗位信息

    Raises:
        HTTPException: 岗位不存在时抛出 404 异常
    """
    position = db.query(Position).filter(Position.position_id == position_id).first()

    if not position:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="岗位不存在")

    return position
